<template>
  <div class="major-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" size="small" class="search-form">
        <el-form-item style="margin-bottom:0;margin-right:8px;">
          <el-input v-model="searchForm.major" placeholder="专业关键字" style="width:140px;" />
        </el-form-item>
        <el-form-item style="margin-bottom:0;margin-right:8px;">
          <el-input v-model="searchForm.department" placeholder="系关键字" style="width:120px;" />
        </el-form-item>
        <el-form-item style="margin-bottom:0;margin-right:8px;">
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
        </el-form-item>
        <el-form-item style="margin-bottom:0;margin-right:8px;">
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
        <el-form-item style="margin-bottom:0;">
          <el-button type="success" :icon="Plus" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table :data="tableData" border style="width: 100%" v-loading="loading" size="small">
        <el-table-column type="index" label="序号" width="60" align="center" :index="indexMethod" fixed="left" />
        <el-table-column prop="major_name" label="专业名称" :min-width="200" show-overflow-tooltip />
        <el-table-column prop="department_name" label="所属系" :min-width="200" show-overflow-tooltip />
        <el-table-column label="操作">
          <template #default="{ row }">
            <div style="display: flex">
              <el-button size="small" :icon="Edit" @click="handleEdit(row)">编辑</el-button>
              <el-button size="small" type="danger" :icon="Delete" @click="handleDelete(row)"
                >删除</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.pageNo"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        size="small"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 添加/编辑对话框 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="30%" class="form-dialog" modal-class="light-modal-mask">
      <el-form :model="dialogForm" label-width="100px" size="small">
        <el-form-item label="专业名称">
          <el-input v-model="dialogForm.major_name"></el-input>
        </el-form-item>
        <el-form-item label="所属系">
          <el-select v-model="dialogForm.major_department_id" placeholder="请选择系">
            <el-option
              v-for="item in departmentList"
              :key="item.department_id"
              :label="item.department_name"
              :value="item.department_id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button size="small" @click="dialogVisible = false">取消</el-button>
          <el-button size="small" type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <BaseConfirmDialog
      :visible="confirmVisible"
      title="提示"
      :message="confirmMessage"
      confirm-text="确定"
      cancel-text="取消"
      @confirm="confirmDelete"
      @cancel="confirmVisible=false"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Refresh, Plus, Edit, Delete } from '@element-plus/icons-vue'
import {
  getSpecializedAPI,
  addSpecializedAPI,
  updateSpecializedAPI,
  deleteSpecializedAPI
} from '@/api/admin/specialized.js'
import { getFacultiesAPI } from '@/api/admin/faculties.js'
import BaseConfirmDialog from '@/components/BaseConfirmDialog.vue'

// 搜索表单
const searchForm = reactive({
  major: '',
  department: ''
})

// 表格数据
const tableData = ref([])

// 加载态
const loading = ref(false)

// 分页
const pagination = reactive({
  pageNo: 1,
  pageSize: 10,
  total: 0
})

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogForm = reactive({
  major_id: '',
  major_name: '',
  major_department_id: ''
})
const isEdit = ref(false)
// 删除确认弹窗
const confirmVisible = ref(false)
const confirmMessage = ref('')
let pendingDeleteId = ''

// 系下拉列表
const departmentList = ref([])

// 获取专业数据
const fetchSpecialized = async () => {
  loading.value = true
  const params = {
    pageNo: pagination.pageNo,
    pageSize: pagination.pageSize,
    major: searchForm.major,
    department: searchForm.department
  }
  try {
    const res = await getSpecializedAPI(params)
    tableData.value = res.list || []
    pagination.total = res.total || 0
  } finally {
    loading.value = false
  }
}

// 获取系数据
const fetchDepartments = async () => {
  const res = await getFacultiesAPI({ pageNo: 1, pageSize: 999 }) // 获取所有系
  departmentList.value = res.list || []
}

onMounted(() => {
  fetchSpecialized()
  fetchDepartments()
})

// 序号（跨页连续）
const indexMethod = (index) => {
  return (pagination.pageNo - 1) * pagination.pageSize + index + 1
}

// 搜索
const handleSearch = () => {
  pagination.pageNo = 1
  fetchSpecialized()
}

// 重置
const handleReset = () => {
  searchForm.major = ''
  searchForm.department = ''
  pagination.pageNo = 1
  pagination.pageSize = 10
  fetchSpecialized()
}

// 添加
const handleAdd = () => {
  isEdit.value = false
  dialogTitle.value = '添加专业'
  dialogForm.major_id = ''
  dialogForm.major_name = ''
  dialogForm.major_department_id = ''
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  isEdit.value = true
  dialogTitle.value = '编辑专业'
  dialogForm.major_id = row.major_id
  dialogForm.major_name = row.major_name
  dialogForm.major_department_id = row.department_id
  dialogVisible.value = true
}

// 删除
const handleDelete = (row) => {
  pendingDeleteId = row.major_id
  confirmMessage.value = `确定要删除专业 "${row.major_name}" 吗？`
  confirmVisible.value = true
}
const confirmDelete = async () => {
  await deleteSpecializedAPI({ major_id: pendingDeleteId })
  confirmVisible.value = false
  fetchSpecialized()
}

// 提交表单
const handleSubmit = async () => {
  if (isEdit.value) {
    // 编辑
    await updateSpecializedAPI(dialogForm)
  } else {
    // 添加
    await addSpecializedAPI({
      major_name: dialogForm.major_name,
      major_department_id: dialogForm.major_department_id
    })
  }
  dialogVisible.value = false
  fetchSpecialized()
}

// 分页大小改变
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchSpecialized()
}

// 当前页改变
const handleCurrentChange = (val) => {
  pagination.pageNo = val
  fetchSpecialized()
}
</script>

<style lang="scss" scoped>
.major-container {
  padding: 8px 20px 20px 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.search-bar {
  display: flex;
  align-items: center;
  padding: 0;
  margin: 0 0 18px 0;
  background: none;
  border: none;
  box-shadow: none;
}
.search-form {
  display: flex;
  align-items: center;
  gap: 0;
  padding: 0;
  margin: 0;
}
.search-form .el-form-item {
  margin-bottom: 0;
  margin-right: 8px;
}
.search-form .el-input__wrapper,
.search-form .el-button {
  height: 26px !important;
  min-height: 26px !important;
  font-size: 13px;
}
.table-card {
  margin-top: 0;
}
.el-table {
  margin-top: 0;
}
.el-pagination {
  margin-top: 6px;
  display: flex;
  justify-content: flex-start;
}
.el-pagination .el-pager li {
  border-radius: 4px;
  border: 1px solid #e4e7ed;
  background: #fff;
  color: #606266;
  min-width: 32px;
  height: 32px;
  line-height: 32px;
  margin: 0 2px;
  font-size: 15px;
  cursor: pointer;
}
.el-pagination .el-pager li.active {
  background: #409eff;
  color: #fff;
  border-color: #409eff;
}
.table-card {
  flex: 1 1 0%;
  min-height: 0;
  display: flex;
  flex-direction: column;
  padding-top: 6px;
}
.table-card :deep(.el-card__body) {
  flex: 1 1 0%;
  min-height: 0;
  display: flex;
  flex-direction: column;
}
.table-card :deep(.el-table) {
  flex: 1 1 auto;
  overflow: auto;
}
.el-pagination {
  margin-top: 8px;
  display: flex;
  justify-content: center;
}
</style>
